/**
 *  处理数据格式
 * */
import { $each, $isEmptyArr, $isEmptyObject, isArray, isNullOrEmpty, isNumber } from './index'

// 数据格式的特殊情况
const dealDataFormatStrategy = {
  chart_scatter_simple(data, rulesOption) {
    data.value.forEach((value, index) => {
      // 散点图比较特殊，第三个值是维度，所以不需要处理第三个值
      if (index !== 2) {
        data.value[index] = Number(value && value.toFixed(rulesOption.numberDigit))
      }
    })
  },
  chart_scatter_basic(data, rulesOption) {
    data.value.forEach((value, index) => {
      // 气泡图比较特殊，第三个值是气泡大小，第四个是维度，所以不需要处理第三个后的值
      if (index < 3) {
        data.value[index] = Number(value && value.toFixed(rulesOption.numberDigit))
      }
    })
  },
  chart_scatter_punch(data, rules, dimensions) {
    data.value.forEach((value, index) => {
      // 打卡-气泡图比较特殊，只需处理第三个值是气泡大小
      if (index === 2) {
        data.value[index] = Number(value && value.toFixed(rules[`${dimensions.yAxisSize}New`]?.numberDigit))
      }
    })
  },
  map_scatter(data, rules, dimensions) {
    const { dataFormatType } = data

    const { numberDigit } = rules[`${dimensions[dataFormatType]}New`] || {
      numberDigit: null
    }
    //气泡大小度量
    if (dataFormatType === 'yAxis' && data.value) {
      // 等于yAxis的时候，是气泡大小/度量，有三个值，前两个是经纬度，不需要转换
      const index = data.value.length - 1
      data.value[index] = handleFixed(data.value[index], numberDigit)
      $each(data.tooltip, (item, key) => {
        data.tooltip[key] = handleFixed(item, rules[`${key}New`]?.numberDigit || null)
      })
    } else {
      //地图颜色度量
      data.value = handleFixed(data.value, numberDigit)
    }
  },
  all(data, rulesOption) {
    data.value.forEach((value, index) => {
      data.value[index] = value && Number(value.toFixed(rulesOption.numberDigit))
    })
  },
  map_flyingLine(data, rules, dimensions, dataFormatType, dataSets) {
    if (isNullOrEmpty(dataFormatType)) {
      return
    }
    const { type } = dataSets
    //飞线地图只需要处理飞线度量
    if (dataFormatType === 'yAxis') {
      const { linesValue = [] } = data
      linesValue.forEach(item => {
        const name = type !== 'STATIC' ? item.name : dimensions[dataFormatType]
        item.value = item.value && Number(item.value.toFixed(rules[`${name}New`]?.numberDigit))
      })
    } else {
      //地图颜色度量
      data.value = handleFixed(data.value, rules[`${dimensions[dataFormatType]}New`]?.numberDigit)
    }
  },
  // 散点特殊数据格式的处理
  specialScatter(data, rules, dimensions) {
    if ($isEmptyArr(data.value)) {
      return
    }
    //X轴度量
    data.value[0] = handleFixed(data.value[0], rules[`${dimensions.xAxisScatter}New`]?.numberDigit)
    //y轴度量
    data.value[1] = handleFixed(data.value[1], rules[`${dimensions.yAxis}New`]?.numberDigit)
  },
  //有分子分母数据格式的处理
  stripProgress(data, rules, dimensions) {
    let { tooltip } = data
    Object.keys(tooltip).map(itemKey => {
      const { value } = tooltip[itemKey]
      tooltip[itemKey].value = handleFixed(value, rules[`${dimensions[itemKey]}New`]?.numberDigit)
    })
    const { yAxis, yAxisBar } = tooltip
    data.value = yAxis.value && yAxisBar.value ? Number(Number(((yAxis.value / yAxisBar.value) * 100).toFixed(2))) : 0
  }
}
//树形图
function treeChart(data, rules, yAxisArr = [], type) {
  data.forEach(item => {
    const { tipInfo, children = [] } = item
    yAxisArr.forEach(itemKey => {
      const { numberDigit } = type === 'STATIC' ? rules['yAxisNew'] || {} : rules[`${itemKey}New`] || {}
      tipInfo[itemKey] = handleFixed(tipInfo[itemKey], numberDigit)
    })
    if (!$isEmptyArr(children)) {
      treeChart(children, rules, yAxisArr, type)
    }
  })
}

function handleFixed(value, numberDigit) {
  return value ? (!isNullOrEmpty(numberDigit) ? Number(Number(value).toFixed(numberDigit)) : value) : 0
}
//有分子分母的组件
const stripComponents = [
  'chart_strip_progress1',
  'chart_strip_percent',
  'chart_strip_progress2',
  'chart_strip_progress3',
  'chart_bar_percent'
]
// 有x轴度量，y轴度量及气泡大小的组件
const scatterComponents = ['chart_scatter_basic', 'chart_scatter_simple']
//其他组件
const otherComponents = ['map_scatter', 'chart_scatter_punch', 'map_flyingLine']

export function handleDealDataFormat(dataSets, rules, componentKey) {
  if (!rules || $isEmptyObject(rules)) {
    return dataSets
  }
  const reg = /^(0|[1-9][0-9]*)$/
  if (dataSets.seriesData) {
    //树形图数据格式
    if (componentKey === 'chart_relation_tree') {
      const {
        dimensions: { yAxis },
        type
      } = dataSets
      treeChart(dataSets.seriesData, rules, yAxis ? yAxis.split('&') : [], type)
    } else {
      $each(dataSets.seriesData, series => {
        $each(series.data, item => {
          if (item) {
            let name = ''
            name = componentKey === 'chart_pie_double' ? item.name : series.name
            if (
                (componentKey === 'map_flyingLine' && dataSets.type === 'STATIC') ||
                (dataSets.type !== 'STATIC' && dataSets.dimensions?.legend)
            ) {
              name = dataSets.dimensions[series.dataFormatType] || name
            }
            const rulesOption = rules[`${name}New`] ||
                rules[`${series.dataFormatType}New`] ||
                rules['yAxisNew'] || {
                  name: '',
                  numberDigit: null,
                  unit: ''
                }
            // const rulesOption = rules.options[series.dataFormatType || 'yAxis'];
            if (stripComponents.includes(componentKey)) {
              dealDataFormatStrategy.stripProgress(item, rules, dataSets.dimensions)
            } else if (scatterComponents.includes(componentKey)) {
              dealDataFormatStrategy.specialScatter(item, rules, dataSets.dimensions)
            } else if (otherComponents.includes(componentKey)) {
              dealDataFormatStrategy[componentKey](item, rules, dataSets.dimensions, series.dataFormatType, dataSets)
            } else if (rulesOption && reg.test(rulesOption.numberDigit)) {
              // 格式化值,雷达图的value为数组
              if (isArray(item.value)) {
                if (dealDataFormatStrategy[componentKey]) {
                  dealDataFormatStrategy[componentKey](item, rulesOption, series.dataFormatType)
                } else {
                  dealDataFormatStrategy.all(item, rulesOption)
                }
              } else if (item.linesValue) {
                dealDataFormatStrategy.map_flyingLine(item, rulesOption, dataSets.dimensions, series.dataFormatType)
              } else if (item.value && isNumber(item.value)) {
                item.value = Number(item.value.toFixed(rulesOption.numberDigit))
              }
            }
          }
        })
      })
    }
  }
  if (dataSets.formatData) {
    const data = componentKey === 'table_rank' ? dataSets.formatData.data : dataSets.formatData
    $each(data, item => {
      if (item.value && isNumber(item.value)) {
        const seriesName = componentKey === 'info_indicatorCard' ? item.yAxis : item.name
        let rule = rules[`${seriesName}New` || 'yAxis']
        if (componentKey === 'info_text') {
          rule = rules[`${dataSets.dimensions['xAxis']}New`]
        }
        //排名轮播表取度量的值
        if (componentKey === 'table_rank') {
          rule = rules[`${dataSets.dimensions['yAxis']}New`]
        }
        if (rule && reg.test(rule.numberDigit)) {
          item.value = Number(item.value.toFixed(rule.numberDigit))
        }
        // 指标卡不需要后缀，排名轮播表也不需要拼后缀,有单独的单位配置项
        if (rule && rule.unit && !['info_indicatorCard', 'table_rank'].includes(componentKey)) {
          item.value = item.value + rule.unit
        }
      }
    })
  }
  return dataSets
}

// 数据格式列处理
const doubleKeys = {
  bi_double_line_bar: {
    fieldKeys: ['yAxis', 'yAxisLine']
  },
  bi_line_Bar: {
    fieldKeys: ['yAxis', 'yAxisLine']
  },
  map_scatter: {
    fieldKeys: ['yAxis', 'yAxisAreaColor']
  },
  map_flyingLine: {
    fieldKeys: ['yAxis', 'yAxisAreaColor']
  },
  chart_scatter_punch: {
    fieldKeys: ['yAxisSize']
  },
  chart_scatter_basic: {
    fieldKeys: ['xAxisScatter', 'yAxis', 'yAxisSize']
  },
  chart_scatter_simple: {
    fieldKeys: ['xAxisScatter', 'yAxis']
  },
  chart_strip_progress2: {
    fieldKeys: ['yAxis', 'yAxisBar']
  },
  chart_strip_percent: {
    fieldKeys: ['yAxis', 'yAxisBar']
  },
  chart_strip_progress3: {
    fieldKeys: ['yAxis', 'yAxisBar']
  },
  chart_strip_progress1: {
    fieldKeys: ['yAxis', 'yAxisBar']
  },
  chart_bar_percent: {
    fieldKeys: ['yAxis', 'yAxisBar']
  },
  chart_bar_double: {
    fieldKeys: ['yAxis', 'yAxisBar']
  },
  bi_forecast_basic_bar: {
    fieldKeys: ['yAxisRealBar', 'yAxisEmptyBar']
  },
  bi_forecast_basic_line: {
    fieldKeys: ['yAxisRealLine', 'yAxisEmptyLine']
  },
  bi_forecast_basic_bar_line: {
    fieldKeys: ['yAxisRealBar', 'yAxisEmptyBar', 'yAxisRealLine', 'yAxisEmptyLine']
  },
  bi_forecast_bouble_y_basic_bar_line: {
    fieldKeys: ['yAxisRealBar', 'yAxisEmptyBar', 'yAxisRealLine', 'yAxisEmptyLine']
  }
}

export function handleColumnSelectData(componentKey, fields) {
  const options = []
  if (!componentKey) {
    return options
  }
  if (doubleKeys[componentKey]) {
    const keys = doubleKeys[componentKey].fieldKeys
    $each(fields, (item, key) => {
      if (keys.includes(key)) {
        options.push({
          key: item.name,
          value: item.key
        })
      }
    })
  } else {
    options.push({
      key: '度量',
      value: 'yAxis'
    })
  }
  return options
}

export function generateComponentFieldFormatMap(block) {
  const { relationData = undefined, props } = block
  const rules = {}
  if (!isNullOrEmpty(relationData)) {
    if (props?.dataFormat?.value) {
      const { options = {} } = props.dataFormat.value
      Object.keys(options).forEach(key => {
        rules[key] = options[key].unitSuffix
        relationData.fields[key]?.relations.map(relation => {
          const dataformat = relation.dataFormat
          if (dataformat) {
            rules[relation.alias || relation.columnAlias || relation.columnName] = options[key].unitSuffix
          }
        })
      })
    }
    // 新版字段映射覆盖旧版的设置
    const selectOptions = handleColumnSelectData(block.componentKey, relationData.fields)

    selectOptions.map(item => {
      // 对遗弃的样式设置的props.dataFormat进行具体度量值的格式化赋值
      const itemValue = block.componentKey === 'info_text' && item.value === 'yAxis' ? 'xAxis' : item.value
      relationData.fields[itemValue]?.relations.map(relation => {
        const dataformat = relation.dataFormat
        if (dataformat) {
          rules[relation.alias || relation.columnAlias || relation.columnName] = dataformat.unit
          rules[`${relation.alias || relation.columnAlias || relation.columnName}New`] = dataformat
        }
      })
    })

    // 静态数据映射
    const staticDataFormat = relationData.dcConfig?.staticDataFormat
    if (staticDataFormat) {
      Object.keys(staticDataFormat).map(key => {
        rules[`${key}New`] = staticDataFormat[key]
        rules[`${key}`] = staticDataFormat[key].unit
      })
    }
    return rules
  }
}
export function getNestedProperty(obj, path) {
  // 将路径字符串按点号（.）分割成数组
  const keys = path.split('.')
  let value = obj

  // 遍历路径数组，逐级访问对象的属性
  for (const key of keys) {
    if (value && typeof value === 'object' && key in value) {
      value = value[key]
    } else {
      // 如果找不到属性或属性不存在于对象中，返回undefined
      return undefined
    }
  }

  // 返回最终的值
  return value
}

/**
 * 替换key，重命名维度or度量的时候用
 * @param {*} obj1
 * @param {*} obj2
 * @returns
 *
 *  示例
 *   const obj1 = { name: 'name1', sex: 'testSex' };
 *   const obj2 = { name: '张三', sex: '李四', address: 'asdfa' };
 *   const result = replaceKeysWithValues(obj1, obj2);
 *   console.log(result); // 输出: { name1: '张三', testSex: '李四', address: 'asdfa' }
 */
export function replaceKeysWithValues(obj1, obj2) {
  const result = {}
  for (const key in obj2) {
    if (obj1.hasOwnProperty(key)) {
      // 如果 key 在 obj1 中存在，使用 obj1 中对应的 value 作为新 key
      result[obj1[key]] = obj2[key]
    } else {
      // 如果 key 不在 obj1 中，直接使用 obj2 中的 key
      result[key] = obj2[key]
    }
  }
  return result
}
